package com.fxwater.api.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.fxwater.api.ApiConst;
import com.fxwater.common.core.domain.AjaxResult;
import com.fxwater.system.domain.SysUser;

/**
 * 
 * @author tzh
 * @date 2018年5月18日 下午4:57:38
 */
@Controller("apiBaseController")
public class ApiBaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected HttpSession getSession() {
        return getRequest().getSession();
    }

    protected SysUser getUser() {
        return (SysUser) getSession().getAttribute(ApiConst.LOGIN_SESSION_KEY);
    }

    protected long getUserId() {
        Long id = 0l;
        SysUser user = getUser();
        if (user != null) {
            id = user.getUserId();
        }
        return id;
    }

    protected String getUserIp() {
        String value = getRequest().getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(value) && !"unknown".equalsIgnoreCase(value)) {
            return value;
        } else {
            return getRequest().getRemoteAddr();
        }
    }
    
//    protected String cookieSign(String value) {
//        try {
//            value = value + ApiConst.PASSWORD_KEY;
//            String sign = Des3EncryptionUtil.encode(ApiConst.DES3_KEY, value);
//            return sign;
//        } catch (Exception e) {
//            logger.error("cookie签名异常：", e);
//        }
//        return null;
//    }
    
    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }
    
    /**
     * 返回成功消息，带数据
     *
     * @param data
     * @return
     */
    public AjaxResult success(Object data) {
        return AjaxResult.success(data);
    }
}
